<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/8
 * Time: 17:20
 */

namespace App\Http\Controllers\Admins;

use App\Http\Controllers\Controller;
use App\Models\ReportModel;
use App\Models\SysModel;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB as DB;


class ReportController  extends Controller
{//报表处理类

    public function ReportUpload()
    {
        return view('admins/report/reportupload');

    }
    public function upload(Request $request)
    {
        $data = $request->all();
        $fileName = $this->saveFile($request);
        //$fileUrl = asset('storage/'.$fileName);
        //dd($fileName);
        return json_encode(['name'=>$fileName,'msg'=>'1']);

        //$fileName = storage_path().'/app/public/'.$fileName;
        //$data = $this->getExcel($fileName);
        //$res = $this->excelToDatabase($data);



    }
    public function saveFile(Request $request)
    {//保存上传的文件
        $file = $request->file('input-b5');
        //dd($file);
        // 文件上传成功,返回地址，失败返回false
        if ($file->isValid()) {

            // 获取文件相关信息
            $originalName = $file->getClientOriginalName(); // 文件原名
            $ext = $file->getClientOriginalExtension();     // 扩展名
            $realPath = $file->getRealPath();   //临时文件的绝对路径
            $type = $file->getClientMimeType();     // image/jpeg
            // 上传文件
            //$filename = date('Y-m-d-H-i-s') . '-' . uniqid() . '.' . $ext;
            $filename = time(). '.' . $ext;//时间戳time();
            // 使用我们新建的uploads本地存储空间（目录）
            //Storage::disk('public')->makeDirectory(date('Y-m'));
            $bool = Storage::disk('public')->put($filename, file_get_contents($realPath));
            //$fileStr = Storage::disk('public')->get($fileName);//获取文件内容
            //var_dump($bool);

        }
        if($ext!='xls')
        {
            return false;
        }
        if($bool)
        {
            return $filename;
        }else{
            return false;
        }
    }
    public function getExcel($fileName)
    {//测试读取excel中的数据
        $file = $fileName;
        //$file  = iconv('utf-8', 'gb2312', $file);
        $encode = mb_detect_encoding($file, array("ASCII",'UTF-8',"GB2312","GBK",'BIG5'));
        $file = mb_convert_encoding($file, 'GB2312', $encode);

        $ReportM = new ReportModel();
        $data = $ReportM->getExcelAllData($file);
        //dd($data);

        $title = array_shift($data);
        $reportformConfig = config('custom.reportform');
        $field = $this->getExcelConfigToField($reportformConfig,$title);
        //dd($field);

        $data = $ReportM->getFieldExcelData($data,$field);
        //现在处理返回的数据已经可以直接写入数据库了
        //dd($data);
        return $data;
    }

    public function excelToDatabase($data)
    {//测试把excel读取的数据写入数据库
        $updateArr = array();
        $insertArr = array();
        $ReportM = new ReportModel();

        foreach ($data as $item)
        {
            if($ReportM->isExist($item["orderNumber"]))
            {//存在更新操作数组
                $updateArr[]= $item;
            }
            else
            {//不存在新增操作数组
                $insertArr[]= $item;
            }
        }

        $ins = false;
        $up = false;
        if(!empty($insertArr))
        {
            //echo "新增数据";
            //var_dump($insertArr);
            $ins = $ReportM->insertData($insertArr);
        }
        if(!empty($updateArr))
        {
            //echo "gengxin 数据";
            //var_dump($updateArr);
            foreach ($updateArr as $k=>$v)
            {
                $up = $ReportM->updateData($v);
            }

        }
        exit;
        if($ins && $up)
        {
            return true;
        }
        return false;
    }
    public function getExcelConfigToField($config,$title)
    {//配置文件里面标注的excel字段转化成excel的列值（A,B...）
        //$config:array ['clickTime'=>'点击时间','goodsTitle'=>'商品信息','goodsId'=>'商品ID'...]
        //$title:array ['B'=>'点击时间','C'=>'商品信息','D'=>'商品ID',...]
        //结果为：array ["clickTime" => "B","goodsTitle" => "C","goodsId" => "D".....]

        //其实可以通过php内置函数来做,(下面两个函数搭配估计差不多)
        //•array_combine — 创建一个数组，用一个数组的值作为其键名，另一个数组的值作为其值
        //•array_flip — 交换数组中的键和值

        $field = [];
        foreach($config as $k=>$v)
        {
            $key = array_search($v, $title);
            if($key)
            {
                $field[$k] = $key;
            }
        }
        return $field;
    }
    public function fileList()
    {

        //$files = Storage::allFiles('public');
        $files = Storage::disk('public')->allFiles();
        //dd($files);
        $res = ['res'=>$files];
        return view('admins/report/filelist',$res);
    }
    public function fileDel(Request $request)
    {//删除无用的文件

        $files = $request->input('file');
        $files = Storage::disk('public')->delete($files);
        $exists = Storage::disk('public')->exists($files);//判断文件是否存在
        if(!$exists)
        {
            return  "文件删除成功";
        }
        else{
            return  "文件删除失败";
        }
        //return turn;//ajax请求吧


    }
    public function xlSyn(Request $request)
    {//同步更新文件
        $files = $request->input('file');
        //$fileName = storage_path().'/app/public/'.$files;
        //$data = $this->getExcel($fileName);
        //$res = $this->excelToDatabase($data);
    }
    public function reportList(Request $request)
    {
        $ReportM = new ReportModel();

        $data = $ReportM->listData();
        //dd($data);

        $res = ['res'=>$data];
        return view('admins/report/reportlist',$res);
    }
    public function reportDel(Request $request)
    {
        $ReportM = new ReportModel();

        $data = $ReportM->listData();
        //dd($data);

        $res = ['res'=>$data];




        return view('admins/report/reportdel',$res);
    }
    public function payment(Request $request)
    {
        $ReportM = new ReportModel();
        //所有的推广位
        $groupList = $ReportM->getGroupByGroupName()->toArray();
        $reportData = $ReportM->paymentView()->toArray();
        //dd($reportData);
        foreach($groupList as  $k => $v)
        {
            $qunid = '';
            $countPay = 0;
            //由于淘宝报表原因必须把[11微信群]改为[11]
            $qun = explode('微信群',$v['groupName']);
            if(count($qun)>=2)
            {//如果大于等于2说明是群主
                $qunid = $qun[0];
            }

            foreach($reportData as $key=>$val)
            {
                if(in_array($v['groupName'],$val))
                {
                    $data[$qunid]['data'][]= $val;
                    $countPay =$countPay + $val['commissionAmount'];
                }
                $data[$qunid]['count']= $countPay;

            }

        }
        //dd($data);
        //因为数据表没有关联，所以需要我这里认为对数据进行分组处理

        $res = ['res'=>$data];
        return view('admins/report/payment',$res);
    }
    public function paying(Request $request)
    {//结算处理
        $data = $request->all();
        if(empty($data['qunid']))
        {
            echo "error, Parameter 'qunid' is not set";
            exit;
        }

        //一次提交只能处理一个群主的信息
        $qunid = $data['qunid'];
        $ids = "ids".$qunid;

        if(empty($data[$ids]))
        {
            echo "error, Parameter 'ids' is not set";
            exit;
        }
        $ids = $data[$ids];
        //获取了ids的值,设值字段为付款后的值,此处进行了事务操作,防止其中sql运行错误导致的，数据异常
        $qun = $qunid."微信群";
        $ReportM = new ReportModel();
        DB::beginTransaction();
        try{

            foreach ($ids as $k => $v)
            {
                //读取一下信息
                $data = $ReportM->getOneInfo($v)->toArray();
                //先要判断有没有支付过(用订单编号来判断)
                $isPay = $ReportM->isPayed($data);
                if($isPay)
                {
                    $result = $ReportM->upeditPayedInfo($v,$qun);
                    //写入付款记录think_paystatus表写入数据
                    if(empty($ReportM->isOneBackupInfo($data)->toArray()))
                    {
                        $res = $ReportM->insertBackupInfo($data);

                        //通过群号获取promoter
                        $promoter = $ReportM->getPromoterByqunId($qunid);
                        $promoterId = $promoter->id;
                        $offsetScore = (int)($data['commissionAmount']*1000);//因为支付宝后台是元为单位,所以最后1000积分为1元
                        //think_points 积分表，每个人的总积分都在这里(买东西和签到的总积分都在这里，积分增长记录在下面的表里面)
                        $ReportM->updateScore($promoterId,$offsetScore);
                        //申请付款后 给积分表也写记录，之后,用积分兑换钱提现--积分记录表-think_exchangepoints
                        $instruction = "后台购买记录提现提现产品".$data['goodsId'];
                        $ReportM->insertOffsetScore($promoterId,$offsetScore,$instruction);

                    }
                    else{
                        throw new Exception("error,'Pay Info' Record already exists");
                    }


                }

            }
            DB::commit();
        } catch (\Exception $e){
            DB::rollback();//事务回滚
            echo $e->getMessage();
            echo $e->getCode();
        }


        //思考要不要给成功页面也计算一下，付款的额度
        $res = ['res'=>''];
        return view('admins/report/paying',$res);


    }
    public function paymentRecord()
    {//支付记录,按时间排序，可以按群名搜索的时间排序
        $ReportM = new ReportModel();

        $data = $ReportM->getPaymentRecord();
        //dd($data);

        $res = ['res'=>$data];
        return view('admins/report/paymentrecord',$res);

    }


}